<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */
    
    /*********************************************************
    *            --== InArch ==--
    *
    * This is the key class to all the admin side data nodes.
    * It is extended into child classes which do all the work.
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 25.05.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
    
    /***
    * Class adminNodeEstae
    ****
    * This class handles the editing of estate pages in INA
    ****
    * @package adminNodes
    * @author Thomas Brandstaetter <tb@essentialmind.com>
    * @version n/a
    * @since 09.05.2011
    * @copyright essentialmind.com 2011
    ***/
    class adminNodeEstate extends adminNode{
        
        /**
         * @brief representes allowed rooms
         */
        private $rooms_array = array(1 => 1,2,3,4,5,6,7,8,9);

        /**
         * @brief representes allowed storeys
         */
        private $storey_array = array(1 => 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

        /**
         * @brief representes allowed rooms
         */
        private $accountrements_array = array(0 => 0,1 => 1,2,3,4);
        
        /**
         * @brief representes allowed categories
         */
        private $category_array = array('A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D');

        /**
         * a data processor. 
         * 
         * @return 
         **/
        function process(){
            if($_POST){
				$this->update();                
			}else{   
				$this->show();
			}
        }
        
        
        protected function show() {
			 
			$this->smarty->assign('federals', $this->db->getAssoc("SELECT id, name FROM estate_federals ORDER BY id"));
			$this->smarty->assign('types', $this->db->getAssoc("SELECT id, name FROM estate_types ORDER BY id"));
			$this->smarty->assign('kinds', $this->db->getAssoc("SELECT id, name FROM estate_kinds ORDER BY id"));
			$this->smarty->assign('floors', $this->db->getAssoc("SELECT id, name FROM estate_floors ORDER BY id"));
			$this->smarty->assign('windows', $this->db->getAssoc("SELECT id, name FROM estate_windows ORDER BY id"));
			$this->smarty->assign('heatings', $this->db->getAssoc("SELECT id, name FROM estate_heatings ORDER BY id"));
			$this->smarty->assign('states', $this->db->getAssoc("SELECT id, name FROM estate_states ORDER BY id"));
			$this->smarty->assign('accountrements', $this->db->getAssoc("SELECT id, name FROM estate_accountrements ORDER BY id"));
			$this->smarty->assign('rooms', $this->rooms_array);   
			$this->smarty->assign('storeys', $this->storey_array);   
			$this->smarty->assign('baths', $this->accountrements_array);   
			$this->smarty->assign('toilets', $this->accountrements_array);   
			$this->smarty->assign('terraces', $this->accountrements_array);   
			$this->smarty->assign('balconies', $this->accountrements_array);
			$this->smarty->assign('loggias', $this->accountrements_array);  
			$this->smarty->assign('categories', $this->category_array);  
			$this->smarty->assign('current_year', date("Y", time()));
			 
			 
			$estate = $this->db->getRow("SELECT    ne.*,
												   ew.name AS window,
												   ef.name AS floor,
												   ea.name AS accountrement,
												   eh.name AS heating,
												   et.name AS type,
												   ek.name as kind,
												   efd.name AS federal,
												   pagemap.title,
												   pagemap.pageid AS pageid
										  FROM pagemap 
										  LEFT JOIN node_estate ne ON pagemap.pageid = ne.id 
										  LEFT JOIN estate_windows ew ON ew.id = ne.window_id
										  LEFT JOIN estate_floors ef ON ew.id = ne.floor_id
										  LEFT JOIN estate_accountrements ea ON ew.id = ne.accountrements_id
										  LEFT JOIN estate_heatings eh ON eh.id = ne.heating_id
										  LEFT JOIN estate_types et ON et.id = ne.type_id
										  LEFT JOIN estate_kinds ek ON ek.id = ne.kind_id
										  LEFT JOIN estate_federals efd ON efd.id = ne.federal_id
										  WHERE pagemap.id = " . $this->pageref);
	
			if ($estate['obtainable_instantly'] == 't') 
				$estate['obtainable_at'] = time();
	
			$this->smarty->assign('estate', $estate);                                                
															
			$this->smarty->assign('pictures', $this->db->getAll("SELECT ep.* 
																   FROM pagemap pm 
																   JOIN estate_pictures ep ON pm.pageid = ep.estate_id 
																   WHERE pm.id = " .$this->pageref . "
																   ORDER BY order_pos ASC"));
																   
																   
			$this->smarty->assign('referenceFolders', $this->db->getAssoc("SELECT om.nodeid, om.title
															   FROM datatype dt
															   JOIN structure st ON st.node_type = dt.id
															   JOIN objectmap om ON om.nodeid = st.id
															   WHERE dt.codeset = " . $this->db->qstr('estateReferenceFolder') ));
															   															   
			$this->smarty->assign('assignedReferenceFolders', $this->db->getCol("SELECT pm.nodeid
															   FROM datatype dt
															   JOIN pagemap pm ON pm.pagetype = dt.id
															   WHERE dt.codeset = " . $this->db->qstr('estate') ."
															     AND pm.pageid = " . (int)$this->object));
        }
        
        
        protected function update() {

			//update database record
			
			// check for new type
	 
			if ($_POST['etype'] == 'new') {
				$this->db->Execute("INSERT INTO estate_types('name', 'url') VALUES (".$_POST['new_etype'].", ".$_POST['new_etype'].")");
				$estateType = $this->db->getOne("SELECT last_value FROM estate_types_id_seq");
			} else {
				$estateType = $_POST['etype'];
			}
			
			$odate = strtotime($_POST['obtainable_Year'].'-'.$_POST['obtainable_Month'].'-'.$_POST['obtainable_Day']);
			
			if (!$odate) 
				$odate = time();
			
			$heating_id =  ((int)$_POST['heating'] == 0) ? 'NULL' : (int)$_POST['heating'];
			$window_id =   ((int)$_POST['window'] == 0) ? 'NULL' : (int)$_POST['window'];
			$state_id =   ((int)$_POST['state'] == 0) ? 'NULL' : (int)$_POST['state'];
			$floor_id =    ((int)$_POST['floor'] == 0) ? 'NULL' : (int)$_POST['floor'];
			$federal_id =  ((int)$_POST['federal'] == 0) ? 'NULL' : (int)$_POST['federal'];
			$kind_id =     ((int)$_POST['kind'] == 0) ? 'NULL' : (int)$_POST['kind'];
			$type_id =     ((int)$_POST['etype'] == 0) ? 'NULL' : (int)$_POST['etype'];
			$accountrements_id =     ((int)$_POST['accountrements'] == 0) ? 'NULL' : (int)$_POST['accountrements'];
			
			$loggias =      ((int)$_POST['loggias'] == 0) ? 'NULL' : (int)$_POST['loggias'];
			$balconies =   ((int)$_POST['balconies'] == 0) ? 'NULL' : (int)$_POST['balconies'];
			$terraces =    ((int)$_POST['terraces'] == 0) ? 'NULL' : (int)$_POST['terraces'];
			
			$sql = "UPDATE node_estate SET 
									 
									 type_id = ".$type_id.",
									 kind_id = ".$kind_id.",
									 federal_id = ".$federal_id.",
									 heating_id = ".$heating_id.",
									 window_id = ".$window_id.",
									 state_id = ".$state_id.",
									 floor_id = ".$floor_id.",
									 accountrements_id = ".$accountrements_id.",
									 city = ".$this->db->qstr($_POST['city']).",
									 zip = ".$this->db->qstr($_POST['zip']).",
									 address = ".$this->db->qstr($_POST['address']).",
									 price = ".(int)$_POST['price'].",
									 space = ".(int)$_POST['space'].",
									 rooms = ".(int)$_POST['rooms'].",
									 storey = ".(int)$_POST['storey'].",
									 category = ".$this->db->qstr($_POST['category']).",
									 obtainable_at = ".$this->db->qstr(date('Y-m-d',$odate)).",
									 obtainable_instantly = '".(int)$_POST['obtainable_instantly']."',
									 bath_rooms = ".(int)$_POST['bath_rooms'].",
									 toilets = ".(int)$_POST['toilets'].",
									 terraces = ". $terraces .",
									 balconies = ".$balconies.",
									 loggia = ". $loggias .",
									 terraces_sm = ".(int)$_POST['terraces_sm'].",
									 balconies_sm = ".(int)$_POST['balconies_sm'].",
									 loggia_sm = ".(int)$_POST['loggia_sm'].",
									 content = ".$this->db->qstr(stripslashes($_POST['content']))."
									 
								 WHERE id = " . $this->object;
								 
			$this->db->Execute($sql);                     
			  
			
			// var_dump($_FILES); die();              
			if($_FILES['pictures']['tmp_name']){
				 foreach($_FILES['pictures']['tmp_name'] as $key => $source){
					 if($source){
						 try{
							 $this->saveImage($this->object, $source);
						 }catch (exception $e){
							 //nothing, just ignore
						 }
					 }
				 }
			}
			
			if($_POST['read_pictures']){
				foreach($_POST['read_pictures'] as $source){
					if($source){
						try{
							$this->saveImage($this->object, $source, null, true);
						}catch (exception $e){
							//nothing, just ignore
						}
					}
				}
			}
			
			if($_FILES['groundplan']['tmp_name']){
				 foreach($_FILES['groundplan']['tmp_name'] as $key => $source){
					 if($source){
						 try{
							 $this->saveImage($this->object, $source, null, false, $this->object);
						 }catch (exception $e){
							 //nothing, just ignore
						 }
					 }
				 }
			}

			if($_POST['read_groundplan']){
				foreach($_POST['read_groundplan'] as $source){
					if($source){
						try{
							$this->saveImage($this->object, $source, null, true, $this->object);
						}catch (exception $e){
							//nothing, just ignore
						}
					}
				}
			}
			 
			/* reference folders */ 
			 
			foreach ($_POST['referenceFolders'] AS $fid => $set) {
			
				if ((int)$set) {

					$isPresent = (int)$this->db->getOne("SELECT count(id)
															FROM pagemap 
															WHERE nodeid = ". $fid ."
															  AND pageid = ". $this->object);
													  
					//fetch origin row	
					$origin = $this->db->getRow("SELECT pm.* 
													FROM datatype dt
													JOIN pagemap pm ON pm.pagetype = dt.id
													WHERE dt.codeset = ".$this->db->qstr('estate')."
													  AND pageid = ". $this->object);
			  
					if (!$isPresent) {
					
						$this->db->Execute("INSERT INTO pagemap(nodeid,
																pageurl,
																pageid,
																pagetype,
																title, 
																owner_gid, 
																owner_uid) 
											VALUES(
	                                                '".(int)$fid."',
	                                                '".$origin['pageurl']."',
	                                                '".(int)$this->object."',
	                                                '".(int)$origin['pagetype']."',
	                                                '".$origin['title']."',
	                                                ".$origin['owner_gid'].",
	                                                ".$origin['owner_uid']."
	                                        )");
	                                        
						
						// fetch new ID                                                             
						$newPageID = $this->db->getOne("SELECT last_value FROM pagemap_id_seq");						
					}
										
				} else {
					$this->db->Execute("DELETE FROM pagemap 
										WHERE nodeid = ". $fid ."
										  AND pageid = ". $this->object);
				}								
			} // foreach ($_POST['referenceFolders'] AS $folder_id) {

			//updates the status of the page (title, wf state)
			$this->updatePageStatus();
			
			// update all titles in referencefolders
// 			$clone_ids = $this->db->getCol("SELECT pagemap.id 
// 											FROM datatype dt
// 											JOIN pagemap ON dt.id = pagemap.pagetype
// 											WHERE pagemap.pageid = " . $this->object);
// 			foreach($clone_ids AS $id) {
// 				$pi = new pageInserter($this->db);
// 				$pi->updatePage($id,$_POST['title']);
// 			}			
						 
			header('Location: '.$this->request.'&confirm=true');
			exit;
	
        
        }
        
        /**
         * Will set the HTML template needed for
         * the child's operation
         * 
         * @return 
         **/
        function setTemplate(){
            $this->setActionTemplate('nodes/editEstate.html');
        }
        
        
		/** 
         * method which will handle a default add action to the
         * dedicated table
         * 
         * @return integer ID of new object
         * @see ajaxAddPage
         * @see ajaxAddNode
         **/
        function addInstance(){
            $this->db->Execute("INSERT INTO node_estate(content) VALUES('')");
            return $this->db->getOne("SELECT last_value FROM node_estate_id_seq");
        }
        
        
        /***
            @details If the $groundplan parameter is set to an estate_id the picture will assigned to it as groundplan
            @purpose    Do the actual image saving
         ***/
        protected function saveImage($estateID, $source, $key=null, $validate=false, $groundplan=-1){
            $upload = new fileUploader();
            $path   = $this->getImagePath();
            
            // error_log( 'trying '.$source.' to '.$path.'<br />' );
            
            if($validate and !$this->url_validate($source)){
                return false;
            }

            if($upload->preparePath($path)){

                if(!@copy($source,$path.'original.jpg')){
                    return;
                }
         
                $source = $path.'original.jpg';
                
                //statistical data -- important
                $size   = getimagesize($source);
                                    
                //create db record
                $newMax = (int) $this->db->getOne("SELECT MAX(order_pos) 
                                                        FROM estate_pictures
                                                        WHERE estate_id = $estateID");
                $newMax++;
                $this->db->Execute("INSERT INTO estate_pictures(estate_id, width, height, filesize, order_pos) 
                                    VALUES($estateID, ".(int)$size[0].", ".(int)$size[1].", ".(int)filesize($source).", $newMax)");
              
                $imageID = $this->db->getOne("SELECT last_value FROM estate_pictures_id_seq");
                
                if ($groundplan != -1) {
                    $this->db->Execute("UPDATE node_estate 
                                        SET groundplan_id = $imageID
                                        WHERE id = $groundplan");
                }

                if($key){
                    $prepend = $key;
                }else{
                    $prepend = $imageID;
                }

                $upload->copyJPEG($source,$path.$prepend.'_image.jpg',1024,768);
                $upload->copyJPEG($source,$path.$prepend.'_thumb_large.jpg',150,150);
                $upload->copyJPEG($source,$path.$prepend.'_thumb.jpg',100,100);

                $upload->createSquare($path.$prepend.'_image.jpg',$path.$prepend.'_square_150.jpg',150); //createSquare
                $upload->createSquare($path.$prepend.'_image.jpg',$path.$prepend.'_square_100.jpg',100); //createSquare
                $upload->createSquare($path.$prepend.'_image.jpg',$path.$prepend.'_square_75.jpg',75); //createSquare
          
                return $imageID;
            }
        }
        
        
        /*
        * @return boolean
        * @param  string $link
        * @desc   erprft die angegeben URL auf Erreichbarkeit (HTTP-Code: 200)
        */
        protected function url_validate( $link ){        
            $url_parts = @parse_url( $link );
            
            if ( empty( $url_parts["host"] ) ) return( false );
            
            if ( !empty( $url_parts["path"] ) )
            {
                $documentpath = $url_parts["path"];
            }
            else
            {
                $documentpath = "/";
            }
            
            if ( !empty( $url_parts["query"] ) )
            {
                $documentpath .= "?" . $url_parts["query"];
            }
            
            $host = $url_parts["host"];
            $port = $url_parts["port"];
            // Now (HTTP-)GET $documentpath at $host";
            
            if (empty( $port ) ) $port = "80";
            $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
            if (!$socket)
            {
                return(false);
                
            }else{
            
                fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
                $http_response = fgets( $socket, 22 );
                
                if ( ereg("200 OK", $http_response, $regs)){
                    return(true);
                    fclose( $socket );
                } else {
                    return(false);
                }
            }
        }
        
    }
?>